package rhelper

import (
	// "gopkg.in/redis.v3"
	"github.com/garyburd/redigo/redis"
	"log"
	"time"
)

// func sentinel(servers []string) *sentinel.Sentinel {
// 	return &sentinel.Sentinel{
// 		Addrs:      servers,
// 		MasterName: "mymaster",
// 		Dial: func(addr string) (redis.Conn, error) {
// 			timeout := 500 * time.Millisecond
// 			log.Println("addr: ", addr)
// 			c, err := redis.DialTimeout("tcp", addr, timeout, timeout, timeout)
// 			if err != nil {
// 				return nil, err
// 			}
// 			return c, nil
// 		},
// 	}
// }

func newPool(server string) *redis.Pool {
	return &redis.Pool{
		MaxIdle:   3,
		MaxActive: 20,
		//IdleTimeout: 240 * time.Second,
		IdleTimeout: 0,
		Dial: func() (redis.Conn, error) {
			// sntnl := sentinel(servers)
			// masterAddr, err := sntnl.MasterAddr()
			// log.Println("masterAddr: ", masterAddr)
			// if err != nil {
			// 	return nil, err
			// }

			c, err := redis.Dial("tcp", server)
			if err != nil {
				return nil, err
			}

			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
}

// func newClient(serverAddr string) *redis.Client {
// 	// client := redis.NewClient(&redis.Options{
// 	// 	Addr:     serverAddr,
// 	// 	Password: "", // no password set
// 	// 	DB:       0,  // use default DB
// 	// })

// 	// return client

// 	client := redis.NewFailoverClient(&redis.FailoverOptions{
// 		MasterName:    "mymaster",
// 		SentinelAddrs: sentinels,
// 	})

// 	return client
// }

const (

	// controller
	ControllerHash = "w:c:"

	// task
	// TaskHash = "w:t:"

	// plan
	PlanHash     = "w:p:"
	PlanIdHolder = "w:i:pid"

	// account
	AccountHash = "w:a:"

	UserHash     = "w:u:"
	UserIdHolder = "w:i:uid"

	// message

	MsgHash   = "w:m:"
	MsgURHash = "w:mu:"

	MsgIdHolder = "w:i:mid"
	// TaskIdHolder = "w:i:tid"

	PowerReport = "w:s:"

	ApnsToken = "w:apns:tk"

	WebAccount = "w:webAcc:"

	EVRelay = "w:ev:relay:"

	OnlineDev = "w:ond:"
	// OnlineUser = "w:onu:"

	WaitKey = "w:wait:"

	//account sort set
	AccountSortSet = "w:sset:a"
)

var (
	// client      *redis.Client
	pool        *redis.Pool
	redisServer = "localhost:6379"
	// sentinels   = []string{"localhost:26379", "localhost:26370", "localhost:26390"}
)

func Pool() *redis.Pool {
	return pool
}

// func RedisClient() *redis.Client {
// 	return client
// }

func init() {
	log.Println("init...")
	pool = newPool(redisServer)
	// client = newClient(redisServer)

}
